package com.shuiyu.cloud.controller;


import com.shuiyu.cloud.entities.CommonResult;
import com.shuiyu.cloud.entities.Payment;
import com.shuiyu.cloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author rjw
 * <p>Description:   </p>
 * @ClassName PaymentController
 * @time 2021/7/13 17:23
 */
@RestController
@Slf4j
public class PaymentController {

    @Resource
    PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/payment/get/{id}")
    public CommonResult query(@PathVariable("id")Long id){
        Payment payment = paymentService.getPaymentById(id);
        return new CommonResult(200,"ok,serverport"+serverPort,payment);

    }


    @PostMapping("/add")
    public CommonResult add(@RequestBody Payment payment){
        paymentService.create(payment);
        log.info(payment.getId().toString());
        System.out.println("payment = " + payment);
        return new CommonResult(200,"ok,serverport"+serverPort,payment.getId());
    }


    @GetMapping("/payment/discovery")
    public Object discovery(){
        //获取服务列表的信息
        List<String> stringList = discoveryClient.getServices();
        stringList.stream().forEach(s->log.info("-----"+s));
        //获取服务的注册实例
        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instanceList.stream().forEach(s->log.info(s.getServiceId()+"\t"+s.getHost()+"\t"+s.getPort()+"\t"+s.getUri()));
        return this.discoveryClient;
    }

    /**
     * 模拟 openfeign调用超时
     * @return
     */
    @GetMapping("/payment/feignTimeout")
    public  String paymentFeignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }



}
